package com.byit.ueditor.hunter;

import com.byit.ueditor.PathFormat;
import com.byit.ueditor.define.AppInfo;
import com.byit.ueditor.define.BaseState;
import com.byit.ueditor.define.MultiState;
import com.byit.ueditor.define.State;
import com.byit.utils.SpringUtil;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
public class FileManager {

	private String dir = null;
	private String rootPath = null;
	private String[] allowFiles = null;
	private int count = 0;
	
	public FileManager ( Map<String, Object> conf ) {

		this.rootPath = (String)conf.get( "rootPath" );
		this.dir = this.rootPath + (String)conf.get( "dir" );
		this.allowFiles = this.getAllowFiles( conf.get("allowFiles") );
		this.count = (Integer)conf.get( "count" );
		
	}
	
	public State listFile ( int index ) {



		// 获取Minio实例
		MinioClient minioClient = SpringUtil.getBean(MinioClient.class);



		File dir = new File( this.dir );
		State state = null;

		if ( !dir.exists() ) {
			return new BaseState( false, AppInfo.NOT_EXIST );
		}
		
		if ( !dir.isDirectory() ) {
			return new BaseState( false, AppInfo.NOT_DIRECTORY );
		}

        List list = new ArrayList<>();


		try {
			Iterable<Result<Item>> it = minioClient.listObjects("ueditor");



	 		it.forEach(a->{
                try {
                    Item item = a.get();
                } catch (InvalidBucketNameException e) {
                    log.error("", e);
                } catch (NoSuchAlgorithmException e) {
                    log.error("", e);
                } catch (InsufficientDataException e) {
                    log.error("", e);
                } catch (IOException e) {
                    log.error("", e);
                } catch (InvalidKeyException e) {
                    log.error("", e);
                } catch (NoResponseException e) {
                    log.error("", e);
                } catch (XmlPullParserException e) {
                    log.error("", e);
                } catch (ErrorResponseException e) {
                    log.error("", e);
                } catch (InternalException e) {
                    log.error("", e);
                }


            });


			if ( index < 0 || index > list.size() ) {
				state = new MultiState( true );
			} else {
				Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count );
				state = this.getState( fileList );
			}



		} catch (XmlPullParserException e) {
			log.error("", e);
		}



		state.putInfo( "start", index );
		state.putInfo( "total", list.size() );
		
		return state;
		
	}
	
	private State getState ( Object[] files ) {
		
		MultiState state = new MultiState( true );
		BaseState fileState = null;
		
		File file = null;
		
		for ( Object obj : files ) {
			if ( obj == null ) {
				break;
			}
			file = (File)obj;
			fileState = new BaseState( true );
			fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) );
			state.addState( fileState );
		}
		
		return state;
		
	}
	
	private String getPath ( File file ) {
		
		String path = file.getAbsolutePath();
		
		return path.replace( this.rootPath, "/" );
		
	}
	
	private String[] getAllowFiles ( Object fileExt ) {
		
		String[] exts = null;
		String ext = null;
		
		if ( fileExt == null ) {
			return new String[ 0 ];
		}
		
		exts = (String[])fileExt;
		
		for ( int i = 0, len = exts.length; i < len; i++ ) {
			
			ext = exts[ i ];
			exts[ i ] = ext.replace( ".", "" );
			
		}
		
		return exts;
		
	}
	
}
